/*
 * @Author: zhangjian 1027229590@qq.com
 * @Date: 2023-05-28 16:42:38
 * @LastEditors: zhangjian 1027229590@qq.com
 * @LastEditTime: 2023-06-28 10:54:44
 * @FilePath: \vehicle-cms\src\utils\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios'
import { Message } from 'element-ui'
import website from './website'
import { Base64 } from 'js-base64'
import { getToken, removeToken } from './auth'

axios.defaults.baseURL = 'https://w39j515696.zicp.fun'
axios.defaults.timeout = 60000
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.interceptors.request.use(
  config => {
    config.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`
    if (getToken()) {
      config.headers['bridata-Auth'] = getToken()
    }
    if (config.text === true) {
      config.headers['Content-Type'] = 'text/plain'
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  response => {
    const res = response
    if (res.data.access_token) {
      // 单独处理登录
      return response.data
    }
    if (res.data.type === 'application/vnd.ms-excel') {
      return response.data
    }
    // if (res.data.code !== 200) {
    //   // 内部业务接口
    //   Message({
    //     message: res.data.msg || '错误',
    //     type: 'error',
    //     duration: 3 * 1000
    //   })
    //   return Promise.reject(res.data)
    // }

    return response.data
  },
  error => {
    if (error && error.response.data.code === 401) {
      Message({
        message: '鉴权失败！请重新登录', // error.response.data.hasOwnProperty('error_description') ? error.response.data.error_description :
        type: 'error',
        duration: 3 * 1000
      })
      location.href = '/'
      window.localStorage.clear()
      removeToken('token')
    }
    return Promise.reject(error.response.data)
  }
)
export default axios
